package api;

import api.utils.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPath;
import com.github.crab2died.ExcelUtils;
import com.github.crab2died.exceptions.Excel4JException;
import lombok.SneakyThrows;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class ApiTest {
    public static final String dir =System.getProperty("user.dir")+File.separator+"data"+File.separator;
    public static final String  filePath =dir+"apitest3.xlsx";

    @SneakyThrows
    public static void main(String[] args) {
        HttpClientUtils.openProxy=false;

        List<String> allBuniess = ExcelToMapUtils.getAllBuniess(filePath);
        //三层循环 思路
        List<String> pathList =new ArrayList<>();
        for (int i = 0; i < allBuniess.size(); i++) { //业务
            //登录业务参数
            //参数读取问题
            String buniess = allBuniess.get(i);
            List<Map<String, Object>> listMap = ExcelToMapUtils.importExcel(filePath, i+1); //参数覆盖
            List<TestResult> bus_results=new ArrayList<>();
            for (Map<String, Object> map : listMap) {
                List<TestResult> results = testCase(buniess, map);  //一组参数
                bus_results.addAll(results);
            }
            String excelPath = saveResultExcel(buniess, bus_results);
            if(StringUtils.isNotBlank(excelPath)){
                pathList.add(excelPath);
            }
        }
        //单独执行
//        List<TestResult> results = testCase("", new HashMap<>());
//        String excelPath = saveResultExcel("空", results);
//        if(StringUtils.isNotBlank(excelPath)){
//            pathList.add(excelPath);
//        }
        //统一发邮件
        EmailUtils.sendEmailsWithAttachments("测试结果","请查收",pathList);
    }

    private static String saveResultExcel(String buniess, List<TestResult> results) throws Excel4JException, IOException {
        if(results.isEmpty()){
            return "";
        }
        SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd(HH_mm)");
        String time = format0.format(System.currentTimeMillis());
        System.out.println(time);
        String path=dir+buniess+"_result_"+time+".xlsx";
        ExcelUtils.getInstance().exportObjects2Excel(results, TestResult.class, path);
        return path;
    }

    /**
     * @param buniess 业务
     * @param map 参数
     */
    private static List<TestResult> testCase(String buniess, Map<String,Object> map){

        List<TestCase> testCases  =getTestCase(buniess); //全部 -》业务关联 参数 过滤

        List<TestResult> results=new ArrayList<>();
        int order=1; //相对编号
        //testcase参数替换问题
        for (TestCase testCase : testCases) { //以前
            HttpResult httpResult = null;
            TestResult result=new TestResult();
            replace(testCase,map);
            if("get".equals(testCase.getType())){
                httpResult = HttpClientUtils.doGet(testCase.getUrl(), testCase.getHeaders());
            }else if("post".equals(testCase.getType())){
                httpResult=HttpClientUtils.doPost(testCase.getUrl(),testCase.getParams(),testCase.getHeaders());
            }else if("postjson".equals(testCase.getType())){
                httpResult=HttpClientUtils.doPostJson(testCase.getUrl(),testCase.getParams(),testCase.getHeaders());
            }
            System.out.println(testCase+" "+httpResult);

            //检查点
            if(httpResult.getCode()==200){
               addCheckPonit(order,httpResult.getMsg(),map,result);
            }
            order++;
            //提取json结果
            if(httpResult.getCode()==200&&StringUtils.isNotBlank(testCase.getJsonCollect())){
                ParamsUtils.addJsonCollectToMap(testCase.getJsonCollect(),httpResult.getMsg(),map);
            }
            if(httpResult.getCode()==200&&StringUtils.isNotBlank(testCase.getRegxCollect())){
                ParamsUtils.addRegxCollectToMap(testCase.getRegxCollect(),httpResult.getMsg(),map);
            }
            result.setCode(httpResult.getCode());
            result.setHttpResult(httpResult.getMsg());
            result.setBuniess(buniess);
            try {
                BeanUtils.copyProperties(result,testCase);
            } catch (Exception e) {
                e.printStackTrace();
            }

            results.add(result);
        }
        map.clear();
        return results;
    }

    //1_equal={"msg":"登录成功","uid":"9CC972DFA2D4481F89841A46FD1B3E7B","code":"1"};2_contains="code":"1";
    private static void addCheckPonit(int order, String msg, Map<String, Object> map,TestResult result) {
        String checkpoint = MapUtils.getString(map, "checkpoint", "");
        result.setScene(MapUtils.getString(map, "scene", ""));
        if (StringUtils.isNotBlank(checkpoint)) {
            Map<String, Object> stringObjectMap = StringToMapUtils.convert2(checkpoint);
            System.out.println(stringObjectMap);
            stringObjectMap.forEach((k,v)->{
                if(k.startsWith(""+order)){
                    if(k.contains("equal")){
                        result.setCheckpoint(k+"="+v);
                        //三元表达式
                        result.setCheckpointResult(msg.equals(v)==true?"检查成功":"检查失败");
                    }else if(k.contains("contains")){
                        result.setCheckpoint(k+"="+v);
                        result.setCheckpointResult(msg.contains(""+v)==true?"检查成功":"检查失败");
                    }
                }
            });
        }
    }


    @SneakyThrows
    private static List<TestCase> getTestCase(String buniess) {
        //反射技术 你把对象的定义给Excel4J框架，框架帮你new
        List<TestCase> list = ExcelUtils.getInstance().readExcel2Objects(filePath, TestCase.class);
        //  List<TestCase> list = ExcelUtils.getInstance().readExcel2Objects(filePath, TestCase.class,1);
        //所有sheet
        // list.forEach(d-> System.out.println(d));
        //lombok 工具代码提示 //jdk8
        List<TestCase> testCases = list.stream().filter(d -> d.getRun().equals("是")&&buniess.equals(d.getBusiness()))
                .sorted(Comparator.comparing(TestCase::getOrder)).
                        collect(Collectors.toList());
//        testCases.forEach(d-> System.out.println(d));
        return testCases;
    }



    private static void replace(TestCase testCase, Map<String, Object> map) {
        testCase.setParams(ParamsUtils.replace(testCase.getParams(),map));
        testCase.setHeaders(ParamsUtils.replace(testCase.getHeaders(),map));
        testCase.setUrl(ParamsUtils.replace(testCase.getUrl(),map));
    }
}
